package queueOJ;

import java.util.LinkedList;
import java.util.Queue;
//队列实现栈
class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if (!queue1.isEmpty()) {
            queue1.offer(x);
        } else if (!queue2.isEmpty()) {
            queue2.offer(x);
        } else {
            //如果模拟栈为空，规定push到queue1
            queue1.offer(x);
        }
    }

    public int pop() {
        if (empty()){
            return -1;
        }
        if (!queue1.isEmpty()) {
            while (queue1.size()!=1) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            while (queue2.size()!=1) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }

    public int top() {
        if (empty()) {
            return -1;
        }
        if (!queue1.isEmpty()) {
            while (queue1.size()!=1) {
                queue2.offer(queue1.poll());
            }
            int val = queue1.peek();
            queue2.offer(queue1.poll());
            return val;
        } else {
            while (queue2.size()!=1) {
                queue1.offer(queue2.poll());
            }
            int val = queue2.peek();
            queue1.offer(queue2.poll());
            return val;
        }

    }

    public boolean empty() {
        //两个队列都为空则“模拟栈”为空
        return queue1.isEmpty() && queue2.isEmpty();
    }
}